# -*- coding: utf-8 -*-
# @Date    : 2016-12-16 17:30:23
# @Author  : fancy (fancy@thecover.cn)

import sqlite3
import mysql.connector

M_HOST = '192.168.64.13'
M_USER = 'fmcm'
M_PWD = 'fmcm'
M_DB = 'fmcmspider'


def get_mysql_connect():
    cnx = mysql.connector.Connect(
        host=M_HOST,
        user=M_USER,
        password=M_PWD,
        database=M_DB,
    )
    cur = cnx.cursor(buffered=True)
    return cnx, cur


def get_sqlite3_connect():
    cnx = sqlite3.connect('weixin.db')
    cur = cnx.cursor()
    return cnx, cur


def main():
    sql1 = 'select name, item_id, `desc` from source where type=1'
    sql2 = 'select id from gzh where wxh=?'
    sql3 = 'insert into gzh(name,wxh,`desc`) values(?,?,?)'
    cnx, cur = get_mysql_connect()
    cur.execute(sql1)
    result = cur.fetchall()
    cnx.close()
    cnx, cur = get_sqlite3_connect()
    count = 0
    for source in result:
        cur.execute(sql2, (source[1], ))
        if cur.fetchall():
            print 'gzh %s exists~' % source[0]
            continue
        count += 1
        cur.execute(sql3, (source[0], source[1], source[2]))
    cnx.commit()
    cnx.close()
    print 'Add new gzh %s' % count
    print 'Done~'

if __name__ == '__main__':
    main()
